<template>
  <div>
    <dialog-edit :visible.sync="dialogVisible" :title="$attrs.Title" ref="userManageEdit" width="1200"
                 height="500" @save="save" :saveLoading="saveLoading" :destroyOnClose="true">
      <template slot="body">
        <!--                <vxe-button @click="dialogVisible = false">返回</vxe-button>-->
        <dym-form :formData="formData" :components="components" :formRules="formRules" class="dymForm"
                  ref="dymForm">
          <template #Parenttaskid>
            <select-task ref="selectTask" :queryValue="queryValue" @change="change"></select-task>
          </template>
        </dym-form>
      </template>
    </dialog-edit>
    <test-dialog :title="'反馈选择'" :preFormData="preFormData" :visible.sync="testDialogVisible" @selectData="selectData"></test-dialog>
    <show-testcase :title="'测试包'" :preFormData="testPagePreFormData" :visible.sync="testPageDialogVisible" @selectData="selectPageData"></show-testcase>
  </div>
</template>

<script>
import dialogEdit from '@/components/element/dialogEdit'
import dymForm from '@/components/element/dymForm'
import SelectProjectModule from "@/components/element/select/SelectProjectModule";
import SelectProjectTest from "@/components/element/select/SelectProjectTest";
import SelectProjectTeam from "@/components/element/select/SelectProjectTeam";
import tipTap from "@/components/element/tipTap";
import testDialog from "@/page/ProjectManage/modules/proTest/testDialog";
import projectTaskApi from "@/api/projectTaskApi"
import projectTestApi from "@/api/projectTestApi"
import bus from '@/components/common/bus';
import showTestcase from "@/page/ProjectManage/modules/task/showTestcase";
import SelectTask from "@/components/element/select/SelectTask";
import projectModuleApi from "@/api/projectModuleApi";

export default {
  components: {
    dialogEdit,
    dymForm,
    SelectProjectModule,
    SelectProjectTest,
    testDialog,
    SelectProjectTeam,
    tipTap,
    SelectTask,
    showTestcase
  },
  computed: {
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (value) {
        this.$emit('update:visible', value)
      }
    }
  },
  props: {
    visible: {
      type: Boolean,
      default() {
        return false;
      }
    },
    formDataP: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    const defaultTime = ['09:00:00', '18:00:00']
    return {
      queryValue: {},
      formData: {},
      testPageDialogVisible: false,
      testPagePreFormData: {},
      testDialogVisible: false,
      preFormData: {},
      saveLoading: false,
      saveNextLoading: false,
      components: [
        {
          label: '任务',
          span: 24,
          selectTitle: '任务',
          slot: true,
          prop: 'Parenttaskid',
          value: 'Parenttaskid',
          attrs: {}
        },
        {
          label: '模块',
          span: 24,
          placeholder: '请选择模块',
          prop: 'Moduleid',
          value: 'Moduleid',
          selectTitle: '模块',
          componentName: SelectProjectModule,
          attrs: {}
        },
        {
          label: '任务状态',
          span: 24,
          placeholder: '请选择任务状态',
          prop: 'Status',
          value: 'Status',
          componentName: 'SelectDiction',
          DictTypeCode: 'TASK_STATUS'
        },
        {
          label: '任务名称',
          span: 24,
          placeholder: '请输入任务名称',
          prop: 'Name',
          value: 'Name',
          componentName: 'vxe-input',
        },
        {
          label: '任务阶段',
          span: 24,
          placeholder: '请选择任务阶段',
          prop: 'Stage',
          value: 'Stage',
          componentName: 'SelectDiction',
          DictTypeCode: 'TASK_STAGE'
        },
        {
          label: '分类',
          span: 24,
          placeholder: '请选择任务分类',
          prop: 'Type',
          value: 'Type',
          componentName: 'SelectDiction',
          DictTypeCode: 'TASK_TYPE'
        },
        {
          label: '反馈',
          span: 24,
          placeholder: '请选择反馈',
          prop: 'TestName',
          value: 'TestName',
          componentName: 'vxe-input',
          attrs: {
            disabled: true,
            readonly: true
          },
          on: {

          }
        },
        // {
        //   label: '测试包',
        //   span: 24,
        //   placeholder: '请选择测试包',
        //   prop: 'openTestPage',
        //   value: 'openTestPage',
        //   componentName: 'vxe-input',
        //   // attrs: {
        //   //   readonly: true
        //   // },
        //   on: {
        //
        //   }
        // },
        {
          label: '指派人',
          span: 24,
          placeholder: '请选择指派人',
          prop: 'Acceptid',
          value: 'Acceptid',
          componentName: SelectProjectTeam,
          attrs: {
          }
        },
        {
          label: '预计时间',
          span: 12,
          placeholder: '请选择',
          prop: 'TaskDate',
          value: 'TaskDate',
          componentName: 'el-date-picker',
          type: 'datetimerange',
          attrs: {
            'picker-options': {},
            'range-separator': 'TO',
            'start-placeholder': '开始日期',
            'end-placeholder': '结束日期',
            'default-time': defaultTime
          }
        },
        {
          label: '优先级',
          span: 6,
          placeholder: '请输入',
          prop: 'Level',
          value: 'Level',
          componentName: 'vxe-input',
          type: 'number',
          attrs: {
            min: 0,
            step: 1,
            max:500
          }
        },
        {
          label: '预计工时',
          span: 6,
          placeholder: '请输入预计工时',
          prop: 'Tasktime',
          value: 'Tasktime',
          componentName: 'vxe-input',
          type: 'number',
          attrs: {
            min: 0,
            step: 1
          }
        },
        {
          label: '描述',
          span: 24,
          placeholder: '请输入描述',
          prop: 'Desc',
          value: 'Desc',
          componentName: tipTap,
          attrs: {
            width: '100%',
            height: '300px'
          }
        },
        // {
        //   label: '备注',
        //   span: 24,
        //   placeholder: '请输入备注',
        //   prop: 'Note',
        //   value: 'Note',
        //   componentName: 'vxe-textarea',
        //   autosize: {
        //     minRows: 6
        //   }
        // },
      ],
      // childrenList: {
      //   label: '父任务',
      //   slot: true,
      //   span: 24,
      //   placeholder: '请输入父任务ID',
      //   prop: 'Parenttaskid',
      //   value: 'Parenttaskid',
      //   // componentName: 'vxe-input',
      //   disabled: true,
      //   maxlength: 30
      // },
      formRules: {
        Parenttaskid: [{required: true, message: '任务分组必填'}],
        // moduleid: [{required: true, message: '请选择模块'}],
        Stage: [{required: true, message: '请选择任务阶段'}],
        Acceptid: [{required: true, message: '请选择负责人'}],
        Name: [{required: true, message: '请填写任务名称'}],
        Status: [{required: true, message: '请选择任务状态'}]
        // TaskDate: [{required: true, message: '请选择开始结束时间'}]
      }
    }
  },
  methods: {
    // 父任务id
    change (a, selectList) {
      if (selectList.length === 1) {
        if (a && a.length > 0) {
          this.formData.Parenttaskid = a[a.length - 1]
          this.formData.Planid = selectList[0].Planid
        }
      }
    },
    //
    selectPageData (a) {
      console.log(a)
      this.formData.TestPageid = a.Id
      this.formData.TestPageName = a.Name
    },
    // 反馈选择
    selectData (d) {
      this.formData.Testid = d.Id
      this.formData.TestName = d.Name
    },
    // 打开反馈
    openTest () {
      this.preFormData = {
        Projectid: this.formData.Projectid
      }
      this.testDialogVisible = true
    },
    // 打开测试包
    openTestPage () {
      this.testPagePreFormData = {
        Projectid: this.formData.Projectid
      }
      this.testPageDialogVisible = true
    },
    //
    setComponents () {
      let that = this
      that.components.filter(it => {
        if (it.prop === 'Testid' || it.prop === 'TestName') {
          it.on = Object.assign(it.on, {
            click: () => {
              that.openTest()
            }
          })
          return true
        }
        if (it.prop === 'openTestPage') {
          it.on = Object.assign(it.on, {
            click: () => {
              that.openTestPage()
            }
          })
        }
      })
    },
    saveNext () {
      this.save('next')
    },
    initFromData () {
      delete this.formData.Type
      delete this.formData.Moduleid
      delete this.formData.Name
      delete this.formData.TestName
      delete this.formData.Testid
      delete this.formData.Acceptid
      delete this.formData.TaskDate
      delete this.formData.Level
      delete this.formData.Tasktime
      delete this.formData.Desc
    },
    save(type) {
      if (this.formData.Projectid || this.$route.params.id) {
        // 构造开始时间、结束时间
        if (!this.formData.TaskDate) {
          this.initTaskDate()
        }
        if (this.formData.TaskDate && this.formData.TaskDate.length === 2) {
          if (typeof this.formData.TaskDate[0] === "number") {
            this.$set(this.formData, 'Started', this.formData.TaskDate[0])
            this.$set(this.formData, 'Ended', this.formData.TaskDate[1])
          } else {
            this.$set(this.formData, 'Started', this.formData.TaskDate[0].getTime())
            this.$set(this.formData, 'Ended', this.formData.TaskDate[1].getTime())
          }
        }
        this.$refs.dymForm.$refs.form.validate().then((valid) => {
          let a = Object.assign(this.formData, {
            Projectid: this.formData.Projectid || this.$route.params.id,
            id: this.formData.Id,
            Classify: '1'
          })
          if (type) {
            this.saveNextLoading = true
          } else {
            this.saveLoading = true
          }
          if (this.formData.Id) {
            projectTaskApi.update(a).then(res => {
              this.$XModal.message({message: res.message, status: res.code === 1 ? 'success' : 'error'})
              if (res.code === 1) {
                this.dialogVisible = false
                // bus.$emit('showTaskByIdClose', '')
                this.$emit('close')
              }
            }).finally(() => {
              this.saveNextLoading = false
              this.saveLoading = false
            })
          } else {
            projectTaskApi.create(a).then(res => {
              this.$XModal.message({message: res.message, status: res.code === 1 ? 'success' : 'error'})

              if (res.code === 1) {
                this.formDataP.Taskid = res.id
                this.updateTest()
                if (type) {
                  this.initFromData()
                } else {
                  this.dialogVisible = false
                }
                this.$emit('close')
              }
            }).finally(() => {
              this.saveLoading = false
              this.saveNextLoading = false
            })
          }
        }).catch((e) => {
          this.$XModal.message({message: `表单填写错误，请检查`, status: 'error'})
        }).finally(() => {
          this.saveNextLoading = false
          this.saveLoading = false
        })
      } else {
        this.$XModal.message({message: '请从项目中进入', status: 'error'})
      }
    },
    updateTest () {
      this.formDataP.Status = (this.formDataP.Status || '').toString()
      this.formDataP.Type = (this.formDataP.Type || '').toString()
      this.formDataP.Level = (this.formDataP.Level || '').toString()
      this.formDataP.Env = (this.formDataP.Env || '').toString()
      projectTestApi.getEdit({
        id: this.formDataP.Id,
        ...this.formDataP
      }).then(res => {

      })
    },
    initData (row) {
      if (row.hasOwnProperty('Moduleid')) {
        row.Moduleid = row.Moduleid || ''
        row.Moduleid = row.Moduleid.toString()
      }
      if (row.hasOwnProperty('Stage')) {
        row.Stage = row.Stage || ''
        row.Stage = row.Stage.toString()
      }
      if (row.hasOwnProperty('Type')) {
        row.Type = row.Type || ''
        row.Type = row.Type.toString()
      }
      if (row.hasOwnProperty('Level')) {
        row.Level = row.Level.toString()
      }
      if (row.hasOwnProperty('Status')) {
        row.Status = row.Status || '1'
        row.Status = row.Status.toString()
      } else {
        this.$set(row, 'Status', '1')
      }
      if (row.Started && row.Ended) {
        row.TaskDate = [row.Started, row.Ended]
      }
    },
    getTaskById () {
      if (this.formData.id) {
        projectTaskApi.getById(this.formData).then(res => {
          for (let [key, value] of Object.entries(res)) {
            this.$set(this.formData, `${key}`, value)
          }
          this.initData(this.formData)
        })
      } else {
        this.initData(this.formData)
      }
    },
    getTestById () {
      if (this.formData.Testid) {
        projectTestApi.getDataById({id: this.formData.Testid}).then(res => {
          if (res && res.Tests) {
            this.$set(this.formData, `TestName`, res.Tests[0].Name)
          }
        })
      }
    },
    initDateTime () {
      let that = this
      let a = that.components.find(it => it.prop === 'TaskDate')
      if (a) {
        this.$set(a.attrs, 'picker-options', {
          disabledDate (time) {
            let w = new Date().valueOf() - 86400 * 1000
            if (that.formData.PlanStarted) {
              w = new Date(that.formData.PlanStarted).valueOf() - 86400 * 1000
            }
            return w > time.valueOf();
          }
        })
      }
    },
    initTaskDate () {
      let c = new Date().valueOf()
      let datas = [c, c + 86400 * 1000 * 3]
      if (this.formData.PlanStarted) {
        let p = new Date(this.formData.PlanStarted).valueOf()
        if (c < p) {
          datas = [p, p + 86400 * 1000 * 3]
        }
      }
      this.$set(this.formData, 'TaskDate', datas)
    },
    // 模块初始化
    initModule () {
      let that = this
      projectModuleApi.getPage({
        id: this.formData.Projectid,
        pageoffset: 10000
      }).then(res => {
        let p = (res.Modules || []).find(it => {
          return it.Name.trim() === that.formDataP.Modulename.trim()
        })
        if (p) {
          that.formData.Moduleid = p.Id
        }
        this.components.find(it => it.prop === 'Moduleid').attrs.queryValue = {
          id: this.formData.Projectid
        }
      })
    },
    clearValue () {
      this.formData = {}
    }
  },
  watch: {
    dialogVisible: {
      handler (n, o) {
        if (n) {
          let that = this
          that.formData.Projectid = that.formDataP.Projectid
          that.formData.Name = `反馈${that.formDataP.Id}`
          that.formData.TestName = that.formDataP.Name
          that.formData.Testid = that.formDataP.Id
          that.formData.Acceptid = that.formDataP.Acceptid

          that.formData.Type = '8'
          if (this.formData.Projectid) {
            this.components.forEach(it => {
              if (it.prop === 'Moduleid') {
                this.$set(it.attrs, 'queryValue', {})
              }
              if (it.prop === 'Testid' || it.prop === 'Ccid' || it.prop === 'Acceptid' || it.prop === 'Completeid') {
                // it.attrs.queryValue.id = this.formData.Projectid
                this.$set(it.attrs, 'queryValue', {
                  id: this.formData.Projectid
                })
              }
            })
          }
          this.queryValue.id = that.formData.Projectid
          this.$nextTick(() => {
            if (this.$refs.selectTask) {
              this.$refs.selectTask.load = !this.$refs.selectTask.load
            }
          })
          this.initModule()
          this.setComponents()
          this.getTaskById()
          this.getTestById()
          this.initDateTime()
          this.initTaskDate()
        } else {
          this.clearValue()
        }
      }
    }
  }
}
</script>

<style scoped>
.dymForm >>> .el-date-editor {
  width: 100%;
}
</style>
